﻿using LiteDB;
using Microsoft.Extensions.DependencyInjection;
using VIA.Domain;
using VIA.Integration.Domain;
using VIA.Integration.Domain.Production;

namespace VIA.Project.Domain.Services
{
    public interface IRecordService
    {
        Task Record(object product);
    }

    public interface IRecordService<T> : IRecordService where T : IProduct
    {
        ILiteCollection<T> Products { get; }
        Task Record(T product);
        Task SaveDataBase(T product);
        Task SaveCSV(T product);
    }

    public class RecordService<T> : IRecordService<T> where T : IProduct
    {
        IServiceProvider _servcie;
        ICsvStorageService _csvService;
        ILocalDatabaseService _databaseService;
        private ILiteCollection<T> products;
        public DataStorageOption StorageOption { get; set; }

        public ILiteCollection<T> Products { get => products ??= _databaseService.GetCollection<T>(nameof(Products)); }

        public RecordService(IServiceProvider service, ICsvStorageService csvService, ILocalDatabaseService databaseService)
        {
            _servcie = service;
            _csvService = csvService;
            _databaseService = databaseService;
            StorageOption = service.GetRequiredService<IOptionRepository>().Get<DataStorageOption>();
        }

        public Task Record(T product)
        {
            if (StorageOption.IsSaveDatabase)
            {
                var t1 = SaveDataBase(product);
                var t2 = SaveCSV(product);
                return Task.WhenAll(t1, t2);
            }
            return SaveCSV(product);
        }

        [UnitOfWork(true)]
        public Task SaveDataBase(T product)
        {
            return Task.Run(() => Products.Upsert(product));
        }

        public Task Record(object product) => this.Record((T)product);

        public Task SaveCSV(T product)
        {
            return _csvService.SaveAsync(product);
        }
    }

}
